import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/components/number_counter.dart';
import 'package:mall/components/product_price.dart';
import 'package:mall/core/models/cart_list.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/pages/cart/cart_change_model.dart';
import 'package:mall/core/providers/pages/cart/cart_list_model.dart';
import 'package:mall/core/providers/pages/cart/cart_remove_model.dart';
import 'package:mall/core/providers/pages/mine/order/order_check_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/components/check_box.dart';
import 'package:mall/screens/order/order_confirm_screen.dart';
import 'package:provider/provider.dart';

/// 购物车
class CartPage extends StatelessWidget {
  static const routeName = '/CartPage';

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => CartListModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => CartChangeModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => CartRemoveModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => OrderCheckModel(context.read<Api>())),
      ],
      child: Consumer<CartListModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Scaffold(
                appBar: child,
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            case ViewState.error:
              return Scaffold(
                appBar: child,
                body: Center(
                  child: Text(model.errorMessage),
                ),
              );
            case ViewState.success:
              return Scaffold(
                appBar: child,
                body: _BodyWidget(list: model.cartList.carts),
                bottomNavigationBar: _BottomWidget(cartList: model.cartList),
              );
            default:
              return Container();
          }
        },
        child: AppBar(
          title: Text('购物车'),
        ),
      ),
    );
  }
}

/// Tab Item Page
class CartTabItemPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => CartListModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => CartChangeModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => CartRemoveModel(context.read<Api>())),
        ChangeNotifierProvider(create: (context) => OrderCheckModel(context.read<Api>())),
      ],
      child: Consumer<CartListModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return Scaffold(
                appBar: AppBar(
                  title: Text('购物车'),
                ),
                body: _BodyWidget(list: model.cartList.carts),
                bottomNavigationBar: _BottomWidget(cartList: model.cartList),
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  final List<Store> list;

  const _BodyWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      itemBuilder: (context, index) {
        return _StoreItemWidget(store: list[index]);
      },
      separatorBuilder: (context, index) {
        return SizedBox(height: 8);
      },
      itemCount: list.length,
    );
  }
}

/// 店铺名称
class _StoreItemWidget extends StatelessWidget {
  final Store store;

  const _StoreItemWidget({
    Key key,
    @required this.store,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Column(
        children: <Widget>[
          Container(
            height: 45,
            child: Row(
              children: <Widget>[
                Consumer<OrderCheckModel>(
                  builder: (context, model, child) {
                    return CheckBoxWidget(
                      checked: model.getCheckStore(store),
                      onTap: (value) => model.setCheckStore(store, value),
                    );
                  },
                ),
                Container(
                  padding: EdgeInsets.only(right: 6),
                  child: Image.asset(
                    'assets/images/cart/ic_store.png',
                    width: 18,
                    color: Colors.grey,
                  ),
                ),
                Text(
                  "${store.storeName} >",
                  style: TextStyle(color: Colors.grey, fontSize: 16),
                ),
              ],
            ),
          ),
          Divider(height: 1, indent: 16, endIndent: 16),
          ListView.builder(
            physics: NeverScrollableScrollPhysics(),
            shrinkWrap: true,
            itemBuilder: (context, index) {
              return _ProductItemWidget(cart: store.cartList[index]);
            },
            itemCount: store.cartList.length,
          ),
        ],
      ),
    );
  }
}

/// 商品
class _ProductItemWidget extends StatelessWidget {
  final Cart cart;

  const _ProductItemWidget({
    Key key,
    @required this.cart,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Slidable(
      child: Container(
        height: 110,
        child: Row(
          children: <Widget>[
            Consumer<OrderCheckModel>(
              builder: (context, model, child) {
                return CheckBoxWidget(
                  checked: model.getCheckCart(cart),
                  onTap: (value) => model.setCheckCart(cart, value),
                );
              },
            ),
            ClipRRect(
              borderRadius: BorderRadius.all(Radius.circular(4)),
              child: ImageNetwork(
                url: '${cart.productImage}',
                width: 90,
                height: 90,
              ),
            ),
            Expanded(
              child: Container(
                margin: EdgeInsets.all(12),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      cart.productName,
                      style: TextStyle(fontSize: 16),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    Text(
                      '产品属性',
                      style: TextStyle(color: Colors.grey, fontSize: 12),
                    ),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: ProductPrice(list: cart.priceVos),
                        ),
                        _CounterWidget(cart: cart)
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      actionPane: SlidableDrawerActionPane(),
      secondaryActions: <Widget>[
        IconSlideAction(
          color: Colors.red,
          icon: Icons.delete,
          onTap: () => _cartRemove(context, cart.cartId),
        )
      ],
    );
  }

  /// 购物车移除
  void _cartRemove(BuildContext context, int cartId) async {
    CartRemoveModel cartRemoveModel = context.read<CartRemoveModel>();
    EasyLoading.show();
    ViewState viewState = await cartRemoveModel.cartRemove(cartId);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(cartRemoveModel.errorMessage);
        break;
      default:
        CartListModel cartListModel = context.read<CartListModel>();
        cartListModel.refreshData();
        EasyLoading.dismiss();
    }
  }
}

/// 商品数量
class _CounterWidget extends StatelessWidget {
  final Cart cart;

  const _CounterWidget({
    Key key,
    @required this.cart,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return NumberCounter(
      number: cart.quantity,
      updateValueChanged: (value) => _cartChange(context, cart.cartId, value),
    );
  }

  /// 修改数量
  void _cartChange(BuildContext context, int cartId, int quantity) async {
    CartChangeModel cartChangeModel = context.read<CartChangeModel>();
    EasyLoading.show();
    ViewState viewState = await cartChangeModel.cartChange(cartId, quantity);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(cartChangeModel.errorMessage);
        break;
      default:
        CartListModel cartListModel = context.read<CartListModel>();
        cartListModel.refreshData();
        EasyLoading.dismiss();
    }
  }
}

/// 底部统计
class _BottomWidget extends StatelessWidget {
  final CartList cartList;

  const _BottomWidget({
    Key key,
    @required this.cartList,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<OrderCheckModel>(
      builder: (context, model, child) {
        double totalRmb = model.totalRmb(cartList);
        Map<String, double> totalJfbs = model.totalJfbs(cartList);
        int totalQuantity = model.totalQuantity(cartList);
        return Container(
          color: Colors.white,
          height: 52,
          child: Row(
            children: <Widget>[
              CheckBoxWidget(
                checked: model.getCheckAll(cartList),
                onTap: (value) => model.setCheckAll(cartList, value),
              ),
              Expanded(
                child: Text('全选'),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text.rich(
                    TextSpan(
                      text: '合计：',
                      style: TextStyle(fontSize: 14),
                      children: [
                        TextSpan(
                          text: '￥',
                          style: TextStyle(fontSize: 11),
                        ),
                        TextSpan(
                          text: '${totalRmb.toInt()}',
                          style: TextStyle(fontSize: 18),
                        ),
                        ...totalJfbs.entries.map(
                          (e) => TextSpan(
                            text: ' ${e.key}',
                            style: TextStyle(fontSize: 6),
                            children: [
                              TextSpan(
                                text: '${e.value.toInt()}',
                                style: TextStyle(fontSize: 12),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Text(
                    '不含运费',
                    style: TextStyle(color: Colors.grey, fontSize: 11),
                  ),
                ],
              ),
              Container(
                width: 96,
                height: double.maxFinite,
                margin: EdgeInsets.only(left: 8),
                child: model.viewState == ViewState.busy
                    ? RaisedButton(
                        onPressed: null,
                        shape: RoundedRectangleBorder(),
                        child: SizedBox(
                          width: 14,
                          height: 14,
                          child: CircularProgressIndicator(),
                        ),
                      )
                    : RaisedButton(
                        onPressed: () => _orderCheck(context),
                        shape: RoundedRectangleBorder(),
                        child: Text('结算($totalQuantity)'),
                      ),
              ),
            ],
          ),
        );
      },
    );
  }

  void _orderCheck(BuildContext context) async {
    OrderCheckModel model = context.read<OrderCheckModel>();
    EasyLoading.show();
    ViewState viewState = await model.orderCheck(cartList);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(model.errorMessage);
        break;
      default:
        EasyLoading.dismiss();
        Navigator.of(context).pushNamed(
          OrderConfirmScreen.routeName,
          arguments: OrderConfirmScreenArgs(model.cartIdQuantity),
        );
    }
  }
}
